package org.runecore.rs2.event;

import java.util.*;

/**
 * RuneCore Sep 25, 2011
 * 
 * @author Harry Andreas<Harry@RuneCore.org>
 */

public class EventManager {

	/**
	 * Constructor
	 */
	private EventManager() {
		setQueuedEvents(new LinkedList<Event>());
	}
	
	/**
	 * Queues an event
	 * @param e
	 * @param delay
	 * @param reRun
	 */
	public void queueEvent(Event e, boolean reRun) {
		e.reRuns = reRun;
		getQueuedEvents().add(e);
	}

	/**
	 * Processes the <code>Event</code>'s
	 */
	public void processQueuedEvents() {
		if(getQueuedEvents().isEmpty()) {
			return;
		}
		final Iterator<Event> events = getQueuedEvents().iterator();
		while (events.hasNext()) {
			Event e = events.next();
			if (e.ticksLeft > 0) {
				e.ticksLeft--;
			}
			if (e.ticksLeft < 1) {
				try {
					e.runEvent();
				} catch(Exception exception) {
					exception.printStackTrace();
				} finally {
					if (e.reRuns) {
						e.ticksLeft = e.originalTicks;
					} else {
						events.remove();
					}
				}
			}
		}
	}

	/**
	 * A <code>Queue</code> of Queued <code>Event</code>'s
	 */
	private Queue<Event> queuedEvents;

	/**
	 * A instance of the <code>EventManager</code>
	 */
	private static EventManager instance;

	/**
	 * Get's the <code>EventManager</code> instance
	 * 
	 * @return
	 */
	public static EventManager getSingleton() {
		if (instance == null) {
			instance = new EventManager();
		}
		return instance;
	}

	/**
	 * @return the queuedEvents
	 */
	private Queue<Event> getQueuedEvents() {
		return queuedEvents;
	}

	/**
	 * @param queuedEvents
	 *            the queuedEvents to set
	 */
	private void setQueuedEvents(Queue<Event> queuedEvents) {
		this.queuedEvents = queuedEvents;
	}

}